# workstation.py
import asyncio
import json
import random
import time
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional, Any, List
import playwright
from playwright.async_api import Page, BrowserContext
from pydantic import BaseModel, Field

import helpr
from browser_manager import BrowserManager, BrowserContextError
from callback_handler import CallbackHandler, EventType
from service.db_service import SqlLiteService, RecordNotFoundError
from exceptions import OperationTimeoutError, PageOperationError
from logger_config import setup_logger


class WorkstationConfig(BaseModel):
    """工作站配置项"""
    initial_url: str = "https://mms.pinduoduo.com/chat-merchant/index.html"
    message_queue_size: int = 100
    operation_timeout: int = 30  # 秒
    retry_intervals: tuple[float, float] = (0.3, 2.1)
    cache_dir: Optional[Path] = None
    reuse_context: bool = True


class WorkstationMetrics(BaseModel):
    """工作站运行时指标"""
    messages_sent: int = 0
    transfers_completed: int = 0
    last_active: datetime = Field(default_factory=datetime.now)
    avg_response_time: float = 0.0
    queue_status: Dict[str, int] = Field(default_factory=dict)


class WorkstationState(BaseModel):
    """工作站状态快照"""
    is_running: bool = False
    page_active: bool = False
    websocket_connected: bool = False
    last_error: Optional[str] = None


class Workstation:
    """客服工作台实例（异步）"""

    def __init__(
            self,
            workstation_id: str,
            browser_manager: BrowserManager,
            db_service: SqlLiteService,
            callback_handler: CallbackHandler,
            config: WorkstationConfig,
            logger: Optional[Any] = None
    ):
        self.work_data = {}
        self.workstation_id = workstation_id
        self.browser_manager = browser_manager
        self.db_service = db_service
        self.callback_handler = callback_handler
        self.config = config
        self.logger = logger or setup_logger("workstation")

        # 运行时状态
        self._browser_context: Optional[BrowserContext] = None
        self._page: Optional[Page] = None
        self._state = WorkstationState()
        self._operation_queue = asyncio.Queue(maxsize=config.message_queue_size)
        self.metrics = WorkstationMetrics()
        self._processing_task: Optional[asyncio.Task] = None
        self._close_dialogs_task: Optional[asyncio.Task] = None

    async def ainit(self, name=None):
        """异步初始化工作台"""
        try:
            # 获取或创建浏览器上下文
            # if self.config.reuse_context:
            #     self._browser_context = await self._get_existing_context()

            if not self._browser_context:
                _, self._browser_context = await self.browser_manager.create_context(self.workstation_id)

            # 初始化页面
            await self._init_page()

            # 启动后台任务
            self._state.is_running = True
            self._processing_task = asyncio.create_task(self._process_operations())
            self.logger.info(f"Workstation {self.workstation_id} initialized")

            # 更新数据库状态
            await self._persist_state(name)
        except Exception as e:
            self.logger.error(f"Initialization failed: {str(e)}")
            await self.aclose()
            raise

    async def _get_existing_context(self) -> Optional[BrowserContext]:
        """从数据库获取已有上下文"""
        try:
            record = await self.db_service.select_data(
                "workstations",
                condition="workstation_id = ?",
                params=(self.workstation_id,),
                single=True
            )
            self.logger.debug(f"查询到工作台记录: {record}")
            return await self.browser_manager.get_context(record["workstation_id"])
        except RecordNotFoundError:
            pass
        return None

    async def _init_page(self):
        """初始化浏览器页面"""
        if not self._browser_context:
            raise BrowserContextError("Browser context not initialized")

        self._page = (
            self._browser_context.pages[0]
            if self._browser_context.pages
            else await self._browser_context.new_page()
        )

        # 配置页面监听
        await self._page.goto(self.config.initial_url)
        await self._configure_page()

        # 判断是否成功进入 initial_url 并发送回调
        current_url = self._page.url
        if self.config.initial_url in current_url:
            self.logger.debug(f"进入工作台: {self.config.initial_url}")
            # 开启自定义弹窗监听
            self._close_dialogs_task = asyncio.create_task(self._monitor_custom_dialogs())
            await self.callback_handler.trigger(
                EventType.PAGE_LOADED,
                self.workstation_id,
                {"url": current_url}
            )
        else:
            self.logger.warning(f"Failed to load initial URL: {self.config.initial_url}")

        self.logger.debug(f"Navigated to {self.config.initial_url}")

    async def _configure_page(self):
        """配置页面事件监听"""
        # 路由配置
        await self._page.route("**", self._handle_route)
        self._page.on("response", self._handle_response)

        # WebSocket监听
        self._page.on("websocket", self._handle_websocket)

        # 防止意外弹窗
        self._page.on("popup", lambda page: None)

        # 监听页面导航并发送回调
        self._page.on("framenavigated", self._handle_navigation)


    async def _monitor_custom_dialogs(self):
        """监听自定义弹窗并自动关闭"""
        time_out = 300
        start_time = time.time()
        while self._state.is_running:
            if time.time() - start_time > time_out:
                self.logger.warning("def[_close_first_prompt]超时退出")
                break

            try:
                # 添加等待间隔降低 CPU 占用
                await asyncio.sleep(0.5)

                # 处理次要按钮
                secondary_button = self._page.locator(".secondary-btn")
                if secondary_button:
                    if await secondary_button.count() > 0:
                        self.logger.debug(f"次要按钮被点击!")
                        await secondary_button.click()

                # 选择一个class="cancel"的组件，并点击
                cancel_button = self._page.get_by_text("今天不再提示").first
                if await cancel_button.count() > 0:
                    await cancel_button.click()

            except Exception as e:
                self.logger.error(f"操作异常：{e}")
                break

    async def enqueue_operation(self, op_type: str, data: Dict):
        """将操作加入队列"""
        if self._operation_queue.full():
            raise asyncio.QueueFull("Operation queue is full")

        await self._operation_queue.put((op_type, data))
        self.metrics.queue_status = {
            "size": self._operation_queue.qsize(),
            "max_size": self.config.message_queue_size
        }
        self.logger.debug(f"Enqueued {op_type} operation")

    async def _process_operations(self):
        """处理操作队列的后台任务"""
        while self._state.is_running:
            op_type, data = await self._operation_queue.get()
            if not op_type:
                break
            try:
                start_time = time.monotonic()

                if op_type == "send_message":
                    await self._send_message(**data)
                elif op_type == "move_conversation":
                    await self._transfer_conversation(**data)

                # 更新指标
                process_time = time.monotonic() - start_time
                self._update_metrics(process_time)

                # 随机间隔防止检测
                await asyncio.sleep(random.uniform(*self.config.retry_intervals))
            except asyncio.CancelledError:
                # 处理取消异常
                pass
            except Exception as e:
                self.logger.error(f"Operation failed: {str(e)}")
                await self._report_error(op_type, data, str(e))
            finally:
                self._operation_queue.task_done()


    def send_message(self, uid: str, message: str):
        """列队发送消息"""
        return self.enqueue_operation("send_message", {"uid": uid, "message": message})

    def move_conversation(self, uid: str, username: str, reason: str):
        """列队转移会话"""
        return self.enqueue_operation("move_conversation", {"uid": uid, "username": username, "reason": reason})

    def _update_metrics(self, process_time: float):
        """更新性能指标"""
        total_time = self.metrics.avg_response_time * self.metrics.messages_sent
        self.metrics.messages_sent += 1
        self.metrics.avg_response_time = (total_time + process_time) / self.metrics.messages_sent
        self.metrics.last_active = datetime.now()

    async def _send_message(self, uid: str, message: str):
        """实际发送消息实现"""
        try:
            selector = f'div[data-random^="{uid}-"]'
            await self._page.wait_for_selector(selector, timeout=self.config.operation_timeout * 1000)

            # 执行操作链
            await self._page.click(selector)
            await self._page.type('textarea#replyTextarea', message)
            await self._page.click('div.send-btn:not([disabled])')

            # 触发回调
            await self.callback_handler.trigger(
                EventType.NEW_MESSAGE,
                self.workstation_id,
                {"uid": uid, "content": message}
            )
        except playwright.async_api.TimeoutError as e:
            raise OperationTimeoutError(f"Send message timeout: {uid}") from e
        except Exception as e:
            raise PageOperationError(f"Failed to send message: {str(e)}") from e

    async def _transfer_conversation(self, uid: str, username: str, reason: str):
        """转移会话实现"""
        try:
            # 提取公共选择器
            base_xpath = f'//div[contains(@data-random, "{uid}-") and contains(@data-random, "-reply")]'
            # 滑动操作
            chat_item = await self._page.wait_for_selector(base_xpath)
            await chat_item.evaluate("el => el.style.transform = 'translateX(-88px)'")

            # 使用显式等待替代固定时间等待
            transfer_btn_xpath = f'{base_xpath}/following-sibling::div[@class="transfer-chat-item-btn"]'
            transfer_btn = await self._page.wait_for_selector(transfer_btn_xpath, state="attached")
            await transfer_btn.click()

            # 执行转移流程
            await self._select_transfer_target(username)
            await self._input_transfer_reason(reason)

            # 还原chat_item的位置
            await chat_item.evaluate("el => el.style.transform = 'translateX(0px)'")

            # 验证操作结果
            message_type, message_text = await self._extract_message_popups_data(
                timeout=self.config.operation_timeout * 1000)

            self.logger.debug(f"验证操作结果完成，结果：{message_type}, {message_text}")

            if message_type != 'success':
                raise PageOperationError(f"转移失败: {message_text}")

            # 触发回调
            await self.callback_handler.trigger(
                EventType.MOVE_CONVERSATION,
                self.workstation_id,
                {"uid": uid, "username": username,  "reason": reason, "result": message_type, "message": message_text}
            )
        except playwright.async_api.TimeoutError as e:
            raise OperationTimeoutError(f"Transfer timeout: {uid}") from e
        except Exception as e:
            raise PageOperationError(f"Transfer failed: {str(e)}") from e

    async def aclose(self):
        """安全关闭工作台"""
        self._state.is_running = False
        try:
            # 等待队列处理完成
            await self._operation_queue.join()
            if self._processing_task:
                self._processing_task.cancel()

            if self._close_dialogs_task:
                self._close_dialogs_task.cancel()

            # 关闭浏览器上下文
            if self._browser_context:
                await self.browser_manager.close_context(
                    self.workstation_id,
                    remove_cache=not self.config.reuse_context
                )

            # 更新数据库状态
            await self.db_service.update_data(
                "workstations",
                {"is_open": False},
                where="workstation_id = ?",
                params=(self.workstation_id,)
            )

            # 触发关闭事件
            await self.callback_handler.trigger(
                EventType.CLOSE_PAGE,
                self.workstation_id,
                {"status": "closed"}
            )
        except Exception as e:
            self.logger.error(f"Close failed: {str(e)}")
            raise
        finally:
            self.logger.info(f"Workstation {self.workstation_id} closed")

    async def health_check(self) -> Dict:
        """健康检查返回详细状态"""
        return {
            "is_running": self._state.is_running,
            "page_active": self._page and not self._page.is_closed(),
            "queue_status": {
                "current": self._operation_queue.qsize(),
                "max": self.config.message_queue_size
            },
            "last_active": self.metrics.last_active,
            "websocket_connected": self._state.websocket_connected
        }

    async def _persist_state(self, name=None):
        """持久化状态到数据库（自动判断插入/更新）"""
        workstation_data = {
            "workstation_id": self.workstation_id,
            "is_open": True,
            "config": self.config.json(),
            "last_activity": datetime.now()
        }
        if name:
            workstation_data["name"] = name

        try:
            # 尝试更新现有记录
            updated = await self.db_service.update_data(
                "workstations",
                workstation_data,
                where="workstation_id = ?",
                params=(self.workstation_id,)
            )

            # 未更新到记录说明不存在
            if updated == 0:
                await self.db_service.insert_data("workstations", workstation_data)

        except Exception as e:
            self.logger.error(f"状态持久化失败: {str(e)}")
            await self._report_error("persist_state", workstation_data, str(e))

    async def _handle_websocket(self, ws):
        """WebSocket消息处理"""
        if "itan-ws.pinduoduo.com" in ws.url:
            self._state.websocket_connected = True
            ws.on("framereceived", self._handle_websocket_frame)
            ws.on("close", lambda: setattr(self._state, "websocket_connected", False))

    async def _handle_websocket_frame(self, data):
        """处理WebSocket数据帧"""
        json_data = None
        # 判断data是否是二进制数据
        if isinstance(data, bytes):
            # self.manager.logger.debug(f"待解析的原始数据：{data}")
            try:
                json_data = helpr.extract_json(data, self.logger)
                self.logger.debug(f"收到websocket消息：{json_data}")

                if json_data:
                    # json转Dict
                    json_data = json.loads(json_data)

                    # 处理订单数据
                    if 'push_data' in json_data:
                        # 遍历json_data['push_data']['data']
                        for item in json_data['push_data']['data']:
                            if 'from' in item['message'] and item['message']['from']['role'] == 'user':
                                order = await self.get_user_orders(item['message']['from']['uid'])
                                item['message']['orders'] = order or []
                    # 回调处理
                    if json_data:
                        await self.callback_handler.trigger(EventType.NEW_MESSAGE, self.workstation_id, json_data)

            except Exception as e:
                self.logger.error(f"websocket接收消息解析出错: {e}")

    async def _report_error(self, op_type: str, data: Dict, error: str):
        """统一错误报告"""
        error_data = {
            "operation": op_type,
            "data": data,
            "error": error,
            "timestamp": datetime.now().isoformat()
        }
        await self.callback_handler.trigger(
            EventType.ERROR,
            self.workstation_id,
            error_data
        )

    async def _handle_navigation(self, frame):
        """处理页面导航并发送回调"""
        current_url = frame.url
        if current_url != self.config.initial_url:
            self.logger.warning(f"Page navigated away from initial URL: {current_url}")
            await self.callback_handler.trigger(
                EventType.PAGE_NAVIGATED,
                self.workstation_id,
                {"url": current_url}
            )
        elif "login" in current_url.lower():
            self.logger.warning(f"Redirected to login page: {current_url}")
            await self.callback_handler.trigger(
                EventType.LOGIN_REDIRECT,
                self.workstation_id,
                {"url": current_url}
            )

    # 保留原始订单处理方法
    async def get_user_orders(self, uid: str) -> List[Dict]:
        """获取用户订单（兼容原始调用）"""
        try:
            result = await self._page.request.post(
                "https://mms.pinduoduo.com/latitude/order/userAllOrder",
                data={"uid": uid, "pageSize": 10}
            )
            return (await result.json()).get("result", {}).get("orders", [])
        except Exception as e:
            self.logger.error(f"获取订单失败: {str(e)}")
            return []

    async def get_assign_cs_list(self):
        """
        获取客服列表以及转移原因列表
        :return:
        """
        try:
            result = await self._page.request.post(url='https://mms.pinduoduo.com/latitude/assign/getAssignCsList',
                                                   data={
                                                       "wechatCheck": True
                                                   })
            return (await result.json()).get("result", {})
        except Exception as e:
            self.logger.error(f"获取客服列表出错：{e}")
            return {}

    async def send_user_help_link(self, link_type: int, uid: str, order_sn: str):
        """
        发送用户帮助链接
        :param link_type: 链接类型
        :param uid: 用户UID
        :param order_sn: 订单号
        :return:
        """
        try:
            result = await self._page.request.post(url='https://mms.pinduoduo.com/latitude/message/sendUserHelpLink',
                                                   data={
                                                       "linkType": link_type,
                                                       "uid": uid,
                                                       "orderSn": order_sn
                                                   })
            json_data = await result.json()
            return json_data.get('success', False), json_data.get('errorMsg', '')
        except Exception as e:
            self.logger.error(f"发送用户帮助链接出错：{e}")
            raise e

    async def send_fav_mall_card(self, uid: str):
        """
        发送商品卡片
        :param uid:
        :return:
        """
        try:
            result = await self._page.request.post(url='https://mms.pinduoduo.com/latitude/message/sendFavMallCard',
                                                   data={
                                                       "uid": uid
                                                   })
            json_data = await result.json()
            return json_data.get('success', False), json_data.get('errorMsg', '')
        except Exception as e:
            self.logger.error(f"发送收藏店铺卡片出错：{e}")
            raise e

    async def get_order_pickup_info(self, order_sn: str):
        """获取订单收件信息"""
        try:
            result = await self._page.request.post(url='https://mms.pinduoduo.com/latitude/afterSales/replenishment/getDetail', data={
                "orderSn": order_sn
            })
            return (await result.json()).get('result', {})
        except Exception as e:
            self.logger.error(f"获取订单收件信息出错：{e}")
            raise e

    async def update_note_tag(self, order_sn: str, remark: str, remark_tag: str = 'RED', remark_tag_name: str = '红色'):
        """
        拼多多订单备注
        :param order_sn:
        :param remark:
        :param remark_tag:
        :param remark_tag_name:
        :return:
        """
        try:
            result = await self._page.request.post(url='https://mms.pinduoduo.com/pizza/order/noteTag/update', data={
                "orderSn": order_sn,
                "remark": remark,
                "remarkTag": remark_tag,
                "remarkTagName": remark_tag_name,
                "source": 1
            })
            return (await result.json()).get('success', False)
        except Exception as e:
            self.logger.error(f"更新订单备注出错：{e}")
            raise e

    async def send_mall_goods_card(self, uid: str, goods_id: int):
        """
        发送商品卡片
        :param uid:
        :param goods_id:
        :return:
        """
        try:
            ret = await self._page.request.post(url='https://mms.pinduoduo.com/plateau/message/send/mallGoodsCard',
                                                data={
                                                    "uid": uid,
                                                    "goods_id": goods_id,
                                                    "biz_type": 2
                                                })
            json_data = await ret.json()
            return json_data.get('success', False)
        except Exception as e:
            self.logger.error(f"发送收藏店铺卡片出错：{e}")
            raise e

    async def recommend_goods(self, uid: str, page_num: int = 1, page_size: int = 10):
        """
        获取推荐商品
        :param uid: 用户UID
        :param page_num: 页数
        :param page_size: 每页数量
        :return:
        """
        try:
            ret = await self._page.request.post(url='https://mms.pinduoduo.com/latitude/goods/recommendGoods', data={
                "pageNum": page_num,
                "pageSize": page_size,
                "uid": uid
            })
            return (await ret.json()).get('result', {})
        except Exception as e:
            self.logger.error(f"获取推荐商品出错：{e}")
            return []

    async def small_transfer_application_apply(
            self,
            order_sn: str,
            transfer_reason: int,
            transfer_amount: int,
            apply_note: str
    ):
        """
        小额打款申请（不是直接打款，需要店铺管理员审核）
        :param order_sn: 订单号
        :param transfer_reason: 申请原因，0=补运费，1=补差价，2=其他
        :param transfer_amount: 打款金额，单位分
        :param apply_note: 打款原因
        :return: success, data, error_msg
        """
        if transfer_reason not in [0, 1, 2]:
            raise ValueError("transfer_reason参数错误，只能为0,1,2")
        try:
            ret = await self._page.request.post(
                url='https://mms.pinduoduo.com/mercury/small_transfer_application/apply', data={
                    "orderSn": order_sn,
                    "transferReason": transfer_reason,
                    "transferAmount": transfer_amount,
                    "applyNote": apply_note
                })
            json_data = await ret.json()
            return json_data.get('success', False), json_data.get('result', {}), json_data.get('errorMsg', '')
        except Exception as e:
            self.logger.error(f"小额打款申请出错：{e}")
            raise e



    async def ask_refund_apply(
            self,
            order_sn: str,
            after_sales_type: int,
            question_type: int,
            refund_amount: int,
            message: str = None,
    ):
        """
        申请售后
        :param order_sn: 拼多多订单号
        :param after_sales_type: 申请类型
        :param question_type: 原因类型
        :param refund_amount: 申请金额，单位是分
        :param message: 发送消息
        :return:
        """
        try:

            reposeInfo = self.get_order_pickup_info(order_sn)

            ret = await self._page.request.post(
                url='https://mms.pinduoduo.com/plateau/message/ask_refund_apply/send', data={
                    "order_sn": order_sn,
                    "manualEditedNote": False,
                    "after_sales_type": after_sales_type,
                    "question_type": question_type,
                    "refund_amount": refund_amount,
                    "message": message,
                    "user_ship_status": 0,
                    "reposeInfo": reposeInfo
                })
            json_data = await ret.json()
            return json_data.get('success', False), json_data.get('result', {}), json_data.get('errorMsg', '')
        except Exception as e:
            self.logger.error(f"申请售后出错：{e}")
            raise e

    async def _select_transfer_target(self, target: str):
        """选择转移目标客服"""
        try:
            # 等待弹窗出现
            dialog = await self._page.wait_for_selector(
                'div[aria-label="转移会话"]:visible',
                timeout=self.config.operation_timeout * 1000
            )

            # 查找目标客服
            rows = await dialog.query_selector_all('div.el-table__body-wrapper > table > tbody > tr')
            for row in rows:
                username_td = await row.wait_for_selector('td.el-table_1_column_1:visible')
                if await username_td.inner_text() == target:
                    transfer_btn = await row.wait_for_selector(
                        'xpath=./descendant::*[text()="转移并微信通知"]',
                        state="visible"
                    )
                    await transfer_btn.click()
                    return
            raise PageOperationError(f"未找到目标客服: {target}")

        except playwright.async_api.TimeoutError as e:
            raise OperationTimeoutError("选择转移目标超时") from e
        except Exception as e:
            self.logger.error(f"选择转移目标出错：{e}")
            raise e

    async def _input_transfer_reason(self, reason: str):
        """输入转移原因"""
        try:
            # 获取弹窗元素
            popup = await self._page.wait_for_selector(
                'div.el-popover:visible',
                timeout=self.config.operation_timeout * 1000
            )

            # 尝试匹配预设原因
            remark_items = await popup.query_selector_all('div.transfer-remark-list > *')
            found = False

            for item in remark_items:
                try:
                    reason_span = await item.wait_for_selector(
                        'span.reason-content:visible',
                        timeout=1000
                    )
                    if await reason_span.inner_text() == reason:
                        submit_btn = await item.wait_for_selector('span.submit-span',timeout=100)
                        await submit_btn.click()
                        found = True
                        break
                except Exception:
                    continue

            self.logger.debug(f"尝试匹配预设原因完成，匹配结果：{found}")

            # 未找到预设原因时输入自定义原因
            if not found:
                other_input = await popup.wait_for_selector('input[placeholder="其它转移原因"]')
                await other_input.fill(reason)
                submit_btn = await popup.wait_for_selector('span.edit-submit-span:visible')
                await submit_btn.click()

        except playwright.async_api.TimeoutError as e:
            raise OperationTimeoutError("输入转移原因超时") from e


    async def _extract_message_popups_data(self, timeout=6000):
        try:
            # 等待消息弹窗出现（最大等待2秒）
            message_box = await self._page.wait_for_selector(
                'div.el-message:visible',
                timeout=timeout
            )

            # 提取消息内容和类型
            message_type = await message_box.get_attribute('class')
            content_element = await message_box.wait_for_selector('p.el-message__content')
            message_text = await content_element.inner_text()

            ret_msg_type = 'none'
            ret_msg_text = message_text

            # 根据消息类型处理
            if 'el-message--warning' in message_type:
                ret_msg_type = 'warning'
            elif 'el-message--success' in message_type:
                ret_msg_type = 'success'
            else:
                ret_msg_type = 'error'

            return ret_msg_type, ret_msg_text

        except playwright.async_api.TimeoutError:
            self.logger.debug("未检测到消息提示框，继续执行")
            return 'none', 'none'
        except Exception as e:
            self.logger.error(f"消息提示处理异常: {str(e)}")
            return 'none', 'none'

    async def _handle_response(self, response):
        if response.status == 200:
            try:
                json_temp = await response.json()
            except:
                json_temp = None
            # self.manager.logger.debug(f"拦截到请求：{response.url}")
            # 待办任务处理
            if 'latitude/assign/getToDoList' in response.url and json_temp:
                self.work_data["toDoList"] = json_temp['result']['toDoList']

            # 已开通的快递处理
            if 'express_wbfrontend/subscription/open/ship/list' in response.url and json_temp:
                self.work_data["shipInfoList"] = json_temp['result']['shipInfoList']

            # 客服和店铺信息
            if 'customService/queryCustomServiceInfo' in response.url and json_temp:
                self.work_data["customServiceInfo"] = json_temp['result']['customServiceInfo']
                self.work_data["mallInfo"] = json_temp['result']['mallInfoResult']

            # 最新的会话列表
            if 'plateau/chat/latest_conversations' in response.url and json_temp:
                # 先判断json_temp['result']['conversations']属性是否存在
                if 'conversations' in json_temp['result']:
                    self.work_data["conversations"] = json_temp['result']['conversations']

            # 3分钟回复率数据
            if 'getRealTimeReplyRate3Min/mallAndCs' in response.url and json_temp:
                self.work_data["replyRate"] = json_temp['result']

    async def _handle_route(self, route):
        await route.continue_()
